#import "Network.h"
#import "PokerTexasHoldem_Client.h"

@implementation CNetwork

@synthesize m_Session;

#pragma mark Events


-(void) setClient:(CPokerTexasHoldem_Client*) client
{
    m_pClient = client;
}

-(void) connectClicked
{
	GKPeerPickerController *mPicker=[[GKPeerPickerController alloc] init];
	mPicker.delegate=self;
	mPicker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
	[mPicker show];
}

// Notifies delegate that the connection type is requesting a GKSession.
- (GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type
{
	GKSession* session = [[GKSession alloc] initWithSessionID:@"BoardGames_ID" 
                                                  displayName: @"Client_Poker" 
                                                  sessionMode:GKSessionModePeer];
    
    [session autorelease];
    return session;
}

// Notifies delegate that the peer was connected to a GKSession.
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
    self.m_Session = session;		// Use a retaining property to take ownership of the session.
	
    session.delegate = self;		// Assumes our object will also become the session's delegate.
    [session setDataReceiveHandler: self withContext:nil];
	
    picker.delegate = nil;			// Remove the picker.
    [picker dismiss];
    [picker autorelease];
    // Start your application.
}

-(void) sendClicked
{
	[m_Session sendDataToAllPeers: [@"Hello World" dataUsingEncoding: NSASCIIStringEncoding] 
                     withDataMode:GKSendDataReliable error:nil];
}

// Read the bytes in data and perform an application-specific action.
- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{	
    int number = 0;
	[data getBytes:&number length:sizeof(int)];
    
    int card_left = number%1000;
    int card_right = number/1000;
    [m_pClient setHoleCards:card_right LeftCard:card_left];
}

#pragma mark GameSessionDelegate

// Indicates a state change for the given peer.
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state
{	
	if (state == GKPeerStateConnected)
	{
        [m_pClient connectOk];
    }	
    
    if(state == GKPeerStateDisconnected)
	{
        //Todo...
    }
}

- (void)viewDidLoad 
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc 
{
    [super dealloc];
}
@end